<?php
class inventory{//后台专用处理同步库存

	var $db;
	var $inventory_config;

	function inventory()
	{
		global $db;
		$this -> db     = & $db;
		
		include_once '../module/inventory/config.inc.php';
		$this->inventory_config = new config();
	}
	function set_all_stocks_buy_product($ids) {
		$this->db->query ( "select id, stock,stock_relations from " . SETMEAL . " where pid in ({$ids})" );
		$pros = $this->db->getRows ();
		
		foreach ( $pros as $pro_item ) {
			
			$new_stock=$this->setting_stock($pro_item['stock_relations'] );
			
			if($new_stock==$pro_item['stock'])continue;
			
			$this->db->query("update ".SETMEAL." SET stock= {$new_stock} where id= {$pro_item['id']} limit 1");
			
		}
	
	}
	
	function set_all_stocks_buy_inventory($id){
		$this->db->query ( "select id, stock,stock_relations from " . SETMEAL . " where stock_relations like '%{$id}_%'" );
		$pros = $this->db->getRows ();
		
		foreach ( $pros as $pro_item ) {
				
			$new_stock=$this->setting_stock($pro_item['stock_relations'] );
				
			if($new_stock==$pro_item['stock'])continue;
				
			$this->db->query("update ".SETMEAL." SET stock= {$new_stock} where id= {$pro_item['id']} limit 1");
				
		}
	}
	
	
	private function setting_stock($stock_relations){
		$inventory_config=$this->inventory_config;
			$product = explode ( ',',$stock_relations );
				
			foreach ( $product as $item ) {
		
				$_t = explode ( '_', $item );
		
				$ids [] = $_t [0];
				$nums [$_t [0]] = $_t [1];
			}
				
			$scl='and id in ('.implode(',', $ids).')';
			$scl2='and productid in ('.implode(',', $ids).')';
				
			$sql="SELECT id,title, stocks,canbuyout FROM ".$inventory_config->db_prefix."products where 1 $scl order by id asc";
				
			$this->db->query($sql);
			$returns=$this->db->getRows();
				
			$sql="SELECT sum(number) as locked,productid FROM ".$inventory_config->db_prefix."orders where timestocked=0 $scl2 group by productid";
			$this->db->query($sql);
			$lock=$this->db->getRows();
				
			foreach ($lock as $item){
				$locked[$item['productid']]=$item['locked'];
			}
			//==================================
			$result_stock=0;
			foreach ($returns as $item){
				if ($nums[$item['id']]){
					$item_stock=$item['stocks']-$item['canbuyout']-$locked[$item['id']];
					$_t=floor($item_stock/$nums[$item['id']]);
				}else{
					$_t=0;
				}
				if($result_stock==0){
					$result_stock=$_t;
				}elseif($result_stock>$_t){
					$result_stock=$_t;
				}
					
					
			}
				
		}
		

}
?>
